import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

// 导入后台管理布局
import AdminLayout from '@/layout/AdminLayout.vue'

// 导入旧页面组件（保留但不使用）
import Home from '@/views/Home.vue'
import TravelPosts from '@/views/TravelPosts.vue'
import Strategies from '@/views/Strategies.vue'
import Community from '@/views/Community.vue'
import Rankings from '@/views/Rankings.vue'
import TripPlanner from '@/views/TripPlanner.vue'
import PostDetail from '@/views/PostDetail.vue'
import UserProfile from '@/views/UserProfile.vue'
import LoginWithQR from '@/views/LoginWithQR.vue'
import Register from '@/views/Register.vue'

const routes: Array<RouteRecordRaw> = [
  // 登录页面（不需要布局）
  {
    path: '/login',
    name: 'Login',
    component: LoginWithQR,
    meta: {
      title: 'fang旅管理系统 - 登录'
    }
  },
  
  // 管理后台路由（使用AdminLayout布局）
  {
    path: '/admin',
    component: AdminLayout,
    redirect: '/admin/dashboard',
    meta: {
      title: '管理后台',
      requiresAuth: true
    },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/admin/Dashboard.vue'),
        meta: {
          title: '数据大屏',
          requiresAuth: true
        }
      },
      {
        path: 'notes',
        name: 'AdminNotes',
        component: () => import('@/views/admin/Notes.vue'),
        meta: {
          title: '游记管理',
          requiresAuth: true
        }
      },
      {
        path: 'guides',
        name: 'AdminGuides',
        component: () => import('@/views/admin/Guides.vue'),
        meta: {
          title: '攻略管理',
          requiresAuth: true
        }
      },
      {
        path: 'qa',
        name: 'AdminQA',
        component: () => import('@/views/admin/QA.vue'),
        meta: {
          title: '问答管理',
          requiresAuth: true
        }
      },
      {
        path: 'users',
        name: 'AdminUsers',
        component: () => import('@/views/admin/Users.vue'),
        meta: {
          title: '用户管理',
          requiresAuth: true
        }
      },
      {
        path: 'roles',
        name: 'AdminRoles',
        component: () => import('@/views/admin/Roles.vue'),
        meta: {
          title: '角色权限',
          requiresAuth: true
        }
      },
      {
        path: 'banners',
        name: 'AdminBanners',
        component: () => import('@/views/admin/Banners.vue'),
        meta: {
          title: '轮播图管理',
          requiresAuth: true
        }
      },
      {
        path: 'comments',
        name: 'AdminComments',
        component: () => import('@/views/admin/Comments.vue'),
        meta: {
          title: '评论管理',
          requiresAuth: true
        }
      },
      {
        path: 'spots',
        name: 'AdminSpots',
        component: () => import('@/views/admin/Spots.vue'),
        meta: {
          title: '排行榜管理',
          requiresAuth: true
        }
      },
      {
        path: 'settings',
        name: 'AdminSettings',
        component: () => import('@/views/admin/Settings.vue'),
        meta: {
          title: '系统设置',
          requiresAuth: true
        }
      }
    ]
  },

  // 默认重定向到管理后台
  {
    path: '/',
    redirect: '/admin/dashboard'
  },

  // ==================== 以下是旧页面路由（保留但不使用） ====================
  {
    path: '/old',
    redirect: '/old/home',
    meta: {
      title: '旧版页面',
      deprecated: true
    },
    children: [
      {
        path: 'home',
        name: 'OldHome',
        component: Home,
        meta: {
          title: 'fang旅 - 首页（旧版）',
          requiresAuth: true,
          deprecated: true
        }
      },
      {
        path: 'posts',
        name: 'OldTravelPosts',
        component: TravelPosts,
        meta: {
          title: '精选游记（旧版）',
          requiresAuth: true,
          deprecated: true
        }
      },
      {
        path: 'posts/:id',
        name: 'OldPostDetail',
        component: PostDetail,
        meta: {
          title: '游记详情（旧版）',
          requiresAuth: true,
          deprecated: true
        }
      },
      {
        path: 'strategies',
        name: 'OldStrategies',
        component: Strategies,
        meta: {
          title: '热门攻略（旧版）',
          requiresAuth: true,
          deprecated: true
        }
      },
      {
        path: 'community',
        name: 'OldCommunity',
        component: Community,
        meta: {
          title: '问答社区（旧版）',
          requiresAuth: true,
          deprecated: true
        }
      },
      {
        path: 'rankings',
        name: 'OldRankings',
        component: Rankings,
        meta: {
          title: '排行榜（旧版）',
          requiresAuth: true,
          deprecated: true
        }
      },
      {
        path: 'trip-planner',
        name: 'OldTripPlanner',
        component: TripPlanner,
        meta: {
          title: '生成行程（旧版）',
          requiresAuth: true,
          deprecated: true
        }
      },
      {
        path: 'profile',
        name: 'OldUserProfile',
        component: UserProfile,
        meta: {
          title: '个人中心（旧版）',
          requiresAuth: true,
          deprecated: true
        }
      },
      {
        path: 'ai',
        name: 'OldAI',
        component: () => import('@/views/ai.vue'),
        meta: {
          title: 'Ai聊天机器人（旧版）',
          deprecated: true
        }
      }
    ]
  },
  
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: {
      title: '注册'
    }
  },

  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: {
      title: '页面未找到'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title as string
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    // 使用用户状态管理检查登录状态
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    const userInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo')
    
    if (!token || !userInfo) {
      // 未登录，跳转到登录页面，并保存当前路径用于登录后跳转
      next({ 
        name: 'Login', 
        query: { redirect: to.fullPath } 
      })
      return
    }
  }

  // 如果已登录用户访问登录页面，重定向到管理后台
  if (to.name === 'Login') {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (token) {
      next({ path: '/admin/dashboard' })
      return
    }
  }

  next()
})

export default router
